package com.ruoyi.system.service.impl;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.NcUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.mapper.NcZhenliaoLogsMapper;
import com.ruoyi.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 牛诊疗单 服务层实现
 *
 * @author ruoyi
 * @date 2019-08-28
 */
@Service
public class NcCowZhenliaoLogsServiceImpl implements INcCowZhenliaoLogsService {


    @Autowired
    private NcZhenliaoLogsMapper ncZhenliaoLogsMapper;


    @Autowired
    private INcOrderService orderService;

    @Autowired
    private INcCowsFilesService cowsFilesService;

    @Autowired
    private INcCowsBirthService ncCowsBirthService;


    @Autowired
    private INcYaoClassService yaoClassService;


    @Autowired
    private INcZhenliaoDrugsService zhenliaoDrugsService;


    @Autowired
    private INcDrugsService ncDrugsService;


    /**
     * 查询诊疗单信息
     *
     * @param zlId 诊疗单ID
     * @return 诊疗单信息
     */
    @Override
    public NcZhenliaoLogs selectNcZhenliaoLogsById(Long zlId) {
        return ncZhenliaoLogsMapper.selectNcZhenliaoLogsById(zlId);
    }

    /**
     * 查询诊疗单列表
     *
     * @param ncZhenliaoLogs 诊疗单信息
     * @return 诊疗单集合
     */
    @Override
    public List<NcZhenliaoLogs> selectNcZhenliaoLogsList(NcZhenliaoLogs ncZhenliaoLogs) {
        return ncZhenliaoLogsMapper.selectNcZhenliaoLogsList(ncZhenliaoLogs);
    }

    /**
     * 查询诊疗单列表
     *
     * @param ncZhenliaoLogs 诊疗单信息
     * @return 诊疗单集合
     */
    @Override
    public List<NcZhenliaoLogs> selectNcZhenliaoLogsListConfirm(NcZhenliaoLogs ncZhenliaoLogs) {
        return ncZhenliaoLogsMapper.selectNcZhenliaoLogsListConfirm(ncZhenliaoLogs);
    }


    /**
     * 新增诊疗单
     *
     * @param ncZhenliaoLogs 诊疗单信息
     * @return 结果
     */
    @Override
    @Transactional
    public AjaxResult insertNcZhenliaoLogs(NcZhenliaoLogs ncZhenliaoLogs, SysUser sysUser) {

        try {

            ncZhenliaoLogs.setZlStatus("3");

            //经手人（当前用户 baseEntity 类型为 varchar 将就存登录名）
            ncZhenliaoLogs.setCreateBy(sysUser.getLoginName());

            // 推送人（当前用户）
            ncZhenliaoLogs.setReportUser(sysUser.getUserId());


            //创建时间
            ncZhenliaoLogs.setCreateTime(ncZhenliaoLogs.getZlTime());


            // 牛耳号
            String cowCode = ncZhenliaoLogs.getCowCode();


            //根据牛耳号查找牛

            NcCowsFiles ncCowsFiles = cowsFilesService.selectCowByCowCode(cowCode);

            //成年奶牛
            if (ncCowsFiles != null) {

                //计算日龄

                //诊疗时间
                Date zlTime = ncZhenliaoLogs.getZlTime();
                Date birthDday = ncCowsFiles.getBirthDay();

                //计算日龄
                long days = (zlTime.getTime() - birthDday.getTime()) / (1000 * 24 * 60 * 60);
                ncZhenliaoLogs.setAgeDays((int) days);

            } else {

                //犊牛
                NcCowsBirth ncCowsBirth = ncCowsBirthService.selectCowByChildCode(cowCode);

                //计算日龄

                //诊疗时间
                Date zlTime = ncZhenliaoLogs.getZlTime();
                Date birthDday = ncCowsBirth.getGivebirthTime();

                long days = (zlTime.getTime() - birthDday.getTime()) / (1000 * 24 * 60 * 60);

                ncZhenliaoLogs.setAgeDays((int) days);
            }

            ncZhenliaoLogsMapper.insertNcZhenliaoLogs(ncZhenliaoLogs);


            ////////////////////////////诊疗药品
            List<Map<String, Object>> yaos = ncZhenliaoLogs.getYaos();


            if (yaos != null) {
                for (Map<String, Object> yao : yaos) {
                    if (String.valueOf(yao.get("drugAmount")).contains(".")){
                        return AjaxResult.error("请输入正确药品剂量");
                    }
                    //诊疗单药品id
                    Long drugId = Long.parseLong(String.valueOf(yao.get("drugId")));
                    //用药数量
                    Integer drugAmount = Integer.parseInt(String.valueOf(yao.get("drugAmount")));
                    //用药方法
                    Integer executeType = Integer.parseInt(String.valueOf(yao.get("executeType")));
                    //用药单位
                    String unit = yao.get("unit").toString();

                    //查询库存中药品
                    NcDrugs ncDrugs = ncDrugsService.selectNcDrugsById(drugId);

                    //校验数量

                    if (ncDrugs != null) {//库存足够

                        if (drugAmount <= 0) {
                            return AjaxResult.error("请输入正确药品剂量");
                        }

                        if (ncDrugs.getStockAmout() > drugAmount) {
                            NcZhenliaoDrugs zhenliaoDrugs = new NcZhenliaoDrugs(drugId, ncDrugs.getDrugCode(), ncDrugs.getDrugName(), executeType, drugAmount, unit, ncZhenliaoLogs.getZlId());
                            zhenliaoDrugs.setCreateTime(new Date());
                            zhenliaoDrugs.setCreateBy(sysUser.getLoginName());
                            zhenliaoDrugsService.insertNcZhenliaoDrugs(zhenliaoDrugs);
                        } else {
                            return AjaxResult.error(ncDrugs.getDrugName() + "库存不足,剩余数量为" + ncDrugs.getStockAmout());
                        }

                    }
                }

            }

            return AjaxResult.success("新增诊疗单成功");

        } catch (Exception e) {
            e.printStackTrace();
        }

        return AjaxResult.error();

    }


    @Override
    public int edit(NcZhenliaoLogs ncZhenliaoLogs) {
        return ncZhenliaoLogsMapper.updateNcZhenliaoLogs(ncZhenliaoLogs);
    }

    /**
     * 修改诊疗单
     *
     * @param ncZhenliaoLogs 诊疗单信息
     * @return 结果
     */
    @Override
    @Transactional
    public AjaxResult updateNcZhenliaoLogs(NcZhenliaoLogs ncZhenliaoLogs) {
        if (ncZhenliaoLogs.getIllMuns() >= 0) {
            ncZhenliaoLogsMapper.updateNcZhenliaoLogs(ncZhenliaoLogs);
        } else {
            return AjaxResult.error("发病次数要为正数");
        }


        //删除原先药品信息
        NcZhenliaoDrugs ncZhenliaoDrugs = new NcZhenliaoDrugs();
        ncZhenliaoDrugs.setZhenliaoId(ncZhenliaoLogs.getZlId());

        List<NcZhenliaoDrugs> zhenliaoDrugsDB = zhenliaoDrugsService.selectNcZhenliaoDrugsList(ncZhenliaoDrugs);

        for (NcZhenliaoDrugs zhenliaoDrugs : zhenliaoDrugsDB) {
            zhenliaoDrugsService.deleteNcZhenliaoDrugsByIds(String.valueOf(zhenliaoDrugs.getZlId()));
        }


        //药
        List<Map<String, Object>> yaos = ncZhenliaoLogs.getYaos();

        if (yaos != null) {
            for (Map<String, Object> yao : yaos) {
                if (String.valueOf(yao.get("drugAmount")).contains(".")){
                    return AjaxResult.error("请输入正确药品剂量");
                }
                //诊疗单药品id
                Long drugId = Long.parseLong(String.valueOf(yao.get("drugId")));
                //用药数量
                Integer drugAmount = Integer.parseInt(String.valueOf(yao.get("drugAmount")));
                //用药方法
                Integer executeType = Integer.parseInt(String.valueOf(yao.get("executeType")));
                //用药单位
                String unit = yao.get("unit").toString();

                //查询库存中药品
                NcDrugs ncDrugs = ncDrugsService.selectNcDrugsById(drugId);

                //校验数量

                if (ncDrugs != null) {

                    if (drugAmount <= 0) {
                        return AjaxResult.error("请输入正确药品剂量");
                    }
                    //库存足够
                    if (ncDrugs.getStockAmout() > drugAmount) {
                        NcZhenliaoDrugs zhenliaoDrugs = new NcZhenliaoDrugs(drugId, ncDrugs.getDrugCode(), ncDrugs.getDrugName(), executeType, drugAmount, unit, ncZhenliaoLogs.getZlId());
                        zhenliaoDrugs.setCreateTime(new Date());
                        zhenliaoDrugsService.insertNcZhenliaoDrugs(zhenliaoDrugs);
                    } else {
                        return AjaxResult.error(ncDrugs.getDrugName() + "库存不足,剩余数量为" + ncDrugs.getStockAmout());
                    }

                }
            }
        }

        return AjaxResult.success("修改成功");
    }

    /**
     * 删除诊疗单对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteNcZhenliaoLogsByIds(String ids) {
        return ncZhenliaoLogsMapper.deleteNcZhenliaoLogsByIds(Convert.toStrArray(ids));
    }

    @Override
    @Transactional
    public int createZlOrderByIds(String ids, SysUser user) {
        NcOrder o = new NcOrder();

        if (StringUtils.isNotEmpty(ids)) {
            //创建诊疗订单
            o.setOrderCode(NcUtils.getOrderCode());
            o.setOrderType(Constants.ORDER_COW_ZHENLIAO);
            o.setOrderTime(new Date());
            o.setCreateTime(new Date());
            o.setCreateBy(user.getLoginName());
            orderService.insertNcOrder(o);

            String[] idArr = Convert.toStrArray(ids);
            for (String id : idArr) {
                NcZhenliaoLogs ncZhenliaoLogs = selectNcZhenliaoLogsById(Long.parseLong(id));
                ncZhenliaoLogs.setOrderId(o.getOrderId());
                ncZhenliaoLogs.setZlStatus("4");
                ncZhenliaoLogs.setCreateBy(user.getLoginName());
                ncZhenliaoLogsMapper.updateNcZhenliaoLogs(ncZhenliaoLogs);
            }

            return 1;
        } else {
            return 0;
        }

    }

    @Override
    @Transactional
    public int askNcZhenliaoLogs(NcZhenliaoLogs ncZhenliaoLogs, SysUser sysUser) {


        // 推送人（当前用户）
        ncZhenliaoLogs.setReportUser(sysUser.getUserId());

        //创建时间
        ncZhenliaoLogs.setCreateTime(new Date());

        ncZhenliaoLogs.setCreateBy(sysUser.getLoginName());


        // 牛耳号
        String cowCode = ncZhenliaoLogs.getCowCode();


        //根据牛耳号查找牛

        NcCowsFiles ncCowsFiles = cowsFilesService.selectCowByCowCode(cowCode);

        //成年奶牛
        if (ncCowsFiles != null) {

            //计算日龄

            //诊疗时间
            Date zlTime = new Date();
            Date birthDday = ncCowsFiles.getBirthDay();

            //计算日龄
            long days = (zlTime.getTime() - birthDday.getTime()) / (1000 * 24 * 60 * 60);
            ncZhenliaoLogs.setAgeDays((int) days);

        } else {

            //犊牛

            NcCowsBirth ncCowsBirth = ncCowsBirthService.selectCowByChildCode(cowCode);
            //计算日龄
            Date zlTime = new Date();
            Date birthDday = ncCowsBirth.getGivebirthTime();

            long days = (zlTime.getTime() - birthDday.getTime()) / (1000 * 24 * 60 * 60);

            ncZhenliaoLogs.setAgeDays((int) days);
        }
        return ncZhenliaoLogsMapper.insertNcZhenliaoLogs(ncZhenliaoLogs);
    }

    @Override
    public int updateZhenliao(String ids) {
        NcZhenliaoLogs o = new NcZhenliaoLogs();

        if (StringUtils.isNotEmpty(ids)) {
            String[] idArr = Convert.toStrArray(ids);
            for (String id : idArr) {
                NcZhenliaoLogs zhenliao = ncZhenliaoLogsMapper.selectNcZhenliaoLogsById(Long.valueOf(id));
                if (Long.valueOf(zhenliao.getZlStatus()) == 5) {
                    NcZhenliaoLogs zhenliaoLog = selectNcZhenliaoLogsById(Long.parseLong(id));
                    zhenliaoLog.setZlId(Long.parseLong(id));
                    zhenliaoLog.setZlType(1);
                    zhenliaoLog.setZlStatus("1");
                    updateNcZhenliaoLogs(zhenliaoLog);
                }
            }

            return 1;
        } else {
            return 0;
        }
    }

    @Override
    @Transactional
    public AjaxResult confirmNcZhenliaoLogs(NcZhenliaoLogs ncZhenliaoLogs, SysUser sysUser) {
        //药

        ncZhenliaoLogsMapper.updateNcZhenliaoLogs(ncZhenliaoLogs);

        List<Map<String, Object>> yaos = ncZhenliaoLogs.getYaos();


        if (yaos != null) {
            for (Map<String, Object> yao : yaos) {
                if (String.valueOf(yao.get("drugAmount")).contains(".")){
                    return AjaxResult.error("请输入正确药品剂量");
                }
                //诊疗单药品id
                Long drugId = Long.parseLong(String.valueOf(yao.get("drugId")));
                //用药数量
                Integer drugAmount = Integer.parseInt(String.valueOf(yao.get("drugAmount")));
                //用药方法
                Integer executeType = Integer.parseInt(String.valueOf(yao.get("executeType")));
                //用药单位
                String unit = yao.get("unit").toString();

                //查询库存中药品
                NcDrugs ncDrugs = ncDrugsService.selectNcDrugsById(drugId);

                //校验数量

                if (ncDrugs != null) {//库存足够

                    if (drugAmount <= 0) {
                        return AjaxResult.error("请输入正确药品剂量");
                    }

                    if (ncDrugs.getStockAmout() > drugAmount) {
                        NcZhenliaoDrugs zhenliaoDrugs = new NcZhenliaoDrugs(drugId, ncDrugs.getDrugCode(), ncDrugs.getDrugName(), executeType, drugAmount, unit, ncZhenliaoLogs.getZlId());
                        zhenliaoDrugs.setCreateTime(new Date());
                        zhenliaoDrugs.setCreateBy(sysUser.getLoginName());
                        zhenliaoDrugsService.insertNcZhenliaoDrugs(zhenliaoDrugs);
                    } else {
                        return AjaxResult.error(ncDrugs.getDrugName() + "库存不足,剩余数量为" + ncDrugs.getStockAmout());
                    }

                }
            }
        }


        return AjaxResult.success("成功");
    }
}
